package 多线程.AQS;

import java.util.concurrent.locks.ReentrantLock;

public class SegmentedLock {
    private final int segments;
    private final ReentrantLock[] locks;

    public SegmentedLock(int segments) {
        this.segments = segments;
        this.locks = new ReentrantLock[segments];
        for (int i = 0; i < segments; i++) {
            locks[i] = new ReentrantLock();
        }
    }

    public void acquireLock(Object key) {
        int segment = getSegment(key);
        locks[segment].lock();
    }

    public void releaseLock(Object key) {
        int segment = getSegment(key);
        locks[segment].unlock();
    }

    private int getSegment(Object key) {
        // 根据键的哈希值和分段数量计算段的索引
        return Math.abs(key.hashCode()) % segments;
    }
}
